﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using DevExpress.XtraLayout.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XCI.Data.Entity;
using XCI.Extensions;
using XCI.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;
using XCI.Windows.DXImagePicker;
using XCI.Windows.Helper;

namespace XCI.Sys.Forms
{
    public partial class FrmModuleEdit : FrmSysBase
    {
        private readonly AsyncWorker formProviderAsyncWorker = new AsyncWorker();
        private readonly AsyncWorker dxImageAsyncWorker = new AsyncWorker();
        private DXImagePickerForm dxImagePicker;
        private bool created;
        private SysModule model;
        private SysModule pmodel;

        public FrmModuleEdit()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keys)
        {
            return OnEsc(msg, keys, () => { EditFormEscResultCancel(); });
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        protected void InitForm()
        {
            formProviderAsyncWorker.RunCallback(e => { e.Result = WinHelper.GetFormProvider(); })
                .CompletCallback(e => { BindFormProvider((List<FormCaptionAttribute>)e.Result); })
                .RunAsync();

            //editWinProvider.PopupPosition = new Point(layWinProvider.Location.X + 10,
            //    editWinProvider.Location.Y + editWinProvider.Size.Height);
            editWinProvider.PopupSize = new Size(0, 300);
            BindModel();
        }

        private void BindFormProvider(List<FormCaptionAttribute> data)
        {
            editWinProvider.Properties.NullValuePrompt = "正在加载...";
            editWinProvider.Metadata = EntityHelper.Get<FormCaptionAttribute>();
            editWinProvider.DataSource = data;
            editWinProvider.Properties.NullValuePrompt = "";
        }

        /// <summary>
        /// 设置数据对象
        /// </summary>
        /// <param name="p_created">是否新建</param>
        /// <param name="p_model">数据对象</param>
        /// <param name="p_parentModel">父节点对象</param>
        public void SetModel(bool p_created, SysModule p_model, SysModule p_parentModel)
        {
            created = p_created;
            model = p_model;
            pmodel = p_parentModel;
            Text = created ? "新建系统菜单模块" : "修改系统菜单模块";
            ckContinue.Visible = ckReserve.Visible = p_created;
        }

        /// <summary>
        /// 绑定数据到界面
        /// </summary>
        private void BindModel()
        {
            BindParentModel(model, pmodel, labParentName, layParentClean);
            WinHelper.SetFormData(layoutPanel, model);
            if (model.WinLargeIcon.IsNotEmpty())
            {
                dxImageAsyncWorker.RunCallback(e => { e.Result = DXImageHelper.GetImage(model.WinLargeIcon); })
                    .CompletCallback(e => { picWinIcon.Image = (Image)e.Result; })
                    .RunAsync();
            }
            else
            {
                layPicWinIcon.Visibility = LayoutVisibility.Never;
            }

            //编辑模式,显示添加标准权限项按钮
            btnAddStandardPermission.Visible = !created;
            editName.Select();
        }

        /// <summary>
        /// 保存数据对象
        /// </summary>
        private bool SaveModel()
        {
            WinHelper.GetFormData(layoutPanel, model);

            var isValid = ValidModel(model);
            if (!isValid) return false;

            if (created)
            {
                return ModuleService.Instance.Insert(model);
            }

            return ModuleService.Instance.Update(model);
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private void FrmModuleEdit_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void CkContinue_CheckedChanged(object sender, EventArgs e)
        {
            ckReserve.Enabled = ckContinue.Checked;
        }

        /// <summary>
        /// 清除父节点
        /// </summary>
        private void btnParentClean_Click(object sender, EventArgs e)
        {
            pmodel = null;
            BindParentModel(model, pmodel, labParentName, layParentClean);
        }

        private void editWinIcon_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (dxImagePicker==null) dxImagePicker = new DXImagePickerForm();
            dxImagePicker.Item16x16.Enabled = false;
            if (dxImagePicker.ShowDialog() == DialogResult.OK)
            {
                if (dxImagePicker.Options.SelectedItem == null) return;
                picWinIcon.Image = dxImagePicker.Options.SelectedItem.Image;
                layPicWinIcon.Visibility = LayoutVisibility.Always;
                model.WinLargeIcon = dxImagePicker.Options.SelectedItem.Name;
                model.WinSmallIcon = dxImagePicker.Options.SelectedItem.RelatedName;
                editWinIcon.Text = model.WinLargeIcon;
            }
        }

        private void editWebCls_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://47.93.100.29/icon");
        }

        /// <summary>
        /// 保存并关闭事件
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!SaveModel()) return;
            if (ckContinue.Checked) //连续保存
            {
                MessageBoxHelper.ShowMessage("保存成功");
                var nmodel = ckReserve.Checked ? ModuleService.Instance.Copy(model) : ModuleService.Instance.NewMenu();
                SetModel(true, nmodel, pmodel);
                BindModel();
            }
            else
            {
                ResultOk();
            }
        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //如果点关闭按钮后想刷新表格就用ResultOk,不刷新用ResultCancel
            ResultOk();
            //ResultCancel();
        }

        private void CkWebFlag_EditValueChanged(object sender, EventArgs e)
        {
            layWebUrl.Enabled = ckWebFlag.Checked;
            layWebCls.Enabled = ckWebFlag.Checked;
        }

        private void CkWinFlag_EditValueChanged(object sender, EventArgs e)
        {
            layDialogFlag.Enabled = ckWinFlag.Checked;
            layWinProvider.Enabled = ckWinFlag.Checked;
            layWinIcon.Enabled = ckWinFlag.Checked;
        }

        private void BtnAddStandardPermission_Click(object sender, EventArgs e)
        {
            var result = ModuleService.Instance.AddStandardPermissionModel(model);
            if (!result) return;
            MessageBoxHelper.ShowMessage("添加成功");
            ResultOk();
        }
    }
}